using Gtk;
using Npgsql;
using System;
using System.Data;

public partial class MainWindow : Gtk.Window
{
	public MainWindow () : base(Gtk.WindowType.Toplevel)
	{
		Build ();
		
		string connectionString= "Server=localhost;Database=dbprueba;User Id=dbprueba;Password=sistemas";
		NpgsqlConnection dbConnection= new NpgsqlConnection(connectionString);
		dbConnection.Open();
		
		DataSet dataSet= new DataSet("dbprueba");
		
		NpgsqlDataAdapter dataAdapter= new NpgsqlDataAdapter("SELECT * FROM articulo order by id", dbConnection);
		
		dataAdapter.MissingSchemaAction= MissingSchemaAction.AddWithKey;
		
//		dataAdapter.TableMappings.Add("Table","articulo");
		
		dataAdapter.Fill(dataSet);
		
		DataTable dataTable= dataSet.Tables[0];
//		DataRow dataRow= dataSet.Tables["articulo"].Rows[0];
		DataRow dataRow= dataTable.Rows[0];
		
		//---- Modificación ----
		dataRow["nombre"]= "articulo " + DateTime.Now;
		dataRow["precio"]= 131;
		
		//---- Elimina el último ----
		int ultimo= dataTable.Rows.Count-1;
		DataRow deleteDataRow= dataTable.Rows[ultimo];
		deleteDataRow.Delete();
		
		//---- Inserción ----
		DataRow newDataRow= dataTable.NewRow();
		newDataRow["nombre"]= "ararticulo nuevo" + DateTime.Now;
		newDataRow["precio"]= 1.5m;
		dataTable.Rows.Add(newDataRow);
		
		
		new NpgsqlCommandBuilder(dataAdapter);
		
		dataAdapter.RowUpdating += delegate(object sender, NpgsqlRowUpdatingEventArgs e) {
			if(e.StatementType == StatementType.Insert) {
				string insertSql= string.Format("{0}; select currval('articulo_id_seq') as id", e.Command.CommandText);
				e.Command.CommandText= insertSql;
			}
			
			Console.WriteLine("RowUpdating Command.CommandText= {0}",e.Command.CommandText);
		};
		
		dataAdapter.Update(dataSet.Tables[0]);
		
		showDataSet(dataSet);
		
		//---- CREA UN XML ----
//		dataSet.WriteXml("dataSet.xml", XmlWriteMode.WriteSchema);
//		dataSet.WriteXml("dataSet.xml", XmlWriteMode.DiffGram);
		
		//---- LEE UN XML ----
//		DataSet dataSet2= new DataSet();
//		dataSet2.ReadXml("dataSet.xml");
//		showDataSet(dataSet2);
		
		dbConnection.Close();
	}
	
	private void showDataSet(DataSet dataSet) {
		foreach(DataTable dataTable in dataSet.Tables)
			showDataTable(dataTable);
	}
	
	private void showDataTable(DataTable dataTable) {
		foreach(DataRow dataRow in dataTable.Rows)
			showDataRow(dataRow);
	}
	
	private void showDataRow(DataRow dataRow) {
		Console.WriteLine("\n");
		foreach(DataColumn dataColumn in dataRow.Table.Columns)
			Console.WriteLine("{0}= {1}", dataColumn.ColumnName, dataRow[dataColumn]);
	}

	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}
}